package com.tc.infinitechat.authenticationservice.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.tc.infinitechat.authenticationservice.constants.oss.OssConstant;
import com.tc.infinitechat.authenticationservice.constants.redis.RedisConstants;
import com.tc.infinitechat.authenticationservice.data.common.sms.SMSRequest;
import com.tc.infinitechat.authenticationservice.data.common.sms.SMSResponse;
import com.tc.infinitechat.authenticationservice.data.user.upload.UploadRequest;
import com.tc.infinitechat.authenticationservice.data.user.upload.UploadResponse;
import com.tc.infinitechat.authenticationservice.service.CommonService;
import com.tc.infinitechat.authenticationservice.utils.OssUtils;
import com.tc.infinitechat.authenticationservice.utils.RandomNumUtil;
import com.tc.infinitechat.authenticationservice.utils.sms.AliyunSmsHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.net.openssl.OpenSSLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CommonServiceImpl
 * @Author 大马鲛鱼丸Gaga
 * @Description TODO
 * @Date 2025/10/8 19:24
 */
@Service
@Slf4j
public class CommonServiceImpl implements CommonService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AliyunSmsHelper aliyunSmsHelper;

    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private OssUtils ossUtils;

    @Override
    public SMSResponse sendSms(SMSRequest smsRequest) {
        String phone = smsRequest.getPhone();

        // 生成6位随机验证码
        String rand_verification_code = RandomUtil.randomNumbers(6);

        log.info("手机号：{}, 已生成随即验证码：{}", phone, rand_verification_code);
        threadPoolTaskExecutor.submit(() -> {
            String signName = "阿里云短信测试";
            String templateCode = "SMS_154950909";
            String templateParam = String.format("{\"code\":\"%s\"}", rand_verification_code);
            aliyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);
        });

        redisTemplate.opsForValue().set(RedisConstants.getCodeKey(phone), rand_verification_code, 5, TimeUnit.MINUTES);
        return new SMSResponse(phone);
    }

    @Override
    public UploadResponse uploadUrl(UploadRequest request) {
        String fileName = request.getFileName();

        String uploadUrl = ossUtils.uploadUrl(OssConstant.BUCKET_NAME, fileName, OssConstant.PICTURE_EXPIRE_TIME);
        String downUrl = ossUtils.downUrl(OssConstant.BUCKET_NAME, fileName);
        UploadResponse response = new UploadResponse();
        response.setUploadUrl(uploadUrl);
        response.setDownloadUrl(downUrl);
        return response;
    }
}
